package com.fenqile.pop.api.demo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Array;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author yaphyao
 * @version 2018/3/7
 * @see com.fenqile.pop.api.demo
 */
public abstract class ApiTest {
    private static Logger logger = LoggerFactory.getLogger(ApiTest.class);
    protected static String apiUrl = "http://pop.api.fenqile.com/router/rest.json";
    protected static String partnerId = "123";
    protected static String partnerKey = "123";
    protected static String v = "1.4";
    protected static String format = "json";

    public abstract void run();

    /**
     * 发送api请求
     *
     * @param jsonObject
     * @return
     */
    public String post(JSONObject jsonObject) {
        Long timestamp = new Date().getTime() / 1000;
        jsonObject.put("timestamp", timestamp);
        jsonObject.put("partner_id", partnerId);
        jsonObject.put("format", format);
        jsonObject.put("v", v);
        String response = "";
        jsonObject.put("sign", md5(jsonObject.toJSONString(), partnerKey));
        try {
            response = PopHttpClientUtil.postJson(jsonObject.toJSONString(), apiUrl);
        } catch (Exception e) {
            logger.error("apiTest error:{}", response);
        }
        return response;
    }


    /**
     * md5加密
     *
     * @param json
     * @param partnerKey
     * @return
     */
    private String md5(String json, String partnerKey) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        String params = "";
        Map<String, Object> map = new TreeMap<String, Object>(jsonObject);
        Set<String> keys = map.keySet();
        keys.remove("partner_key");
        for (String key : keys) {
            Object value = jsonObject.get(key);
            if (value instanceof Array || value instanceof JSONArray) continue;
            if (value != null && StringUtils.isNotBlank(String.valueOf(value))) {
                if (StringUtils.isBlank(params)) {
                    params = key + "=" + String.valueOf(value);
                } else {
                    params += "&" + key + "=" + String.valueOf(value);
                }
            }
        }
        params += "&partner_key=" + partnerKey;
        return Md5Util.getMD5String(params);
    }

}
